package com.imc.platform.base.org.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.imc.api.order.pojo.LessonAtt;
import com.imc.api.order.pojo.UserOrgAccount;
import com.imc.core.utils.ClearTempImg;
import com.imc.core.utils.MenuUtils;
import com.imc.core.utils.MysqlUtil;
import com.imc.core.utils.UploadUtiles;
import com.imc.platform.base.notice.pojo.NoticeAttach;
import com.imc.platform.base.org.pojo.*;
import com.imc.platform.base.org.service.IOrgService;
import com.imc.platform.base.user.pojo.User;
import com.imc.platform.base.user.pojo.UserDesc;
import com.twp.common.component.process.exception.combo.IComboExecptionForTFunc;
import com.twp.common.tuple.ResultDTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.*;

/*
*类描述：组织机构
*开发者：ZL
*创建时间：2018-8-3 14:29:47
*/
@Controller
public class OrgController {

    public static final String imgUrl = "/images/org/";

    @Autowired
    IOrgService iOrgService;
    @Autowired
    MysqlUtil mysqlUtil;
    @Autowired
    MenuUtils menuUtils;
    @Autowired
    UploadUtiles uploadUtiles;
    @Autowired
    ClearTempImg clearTempImg;
    @Autowired
    IComboExecptionForTFunc iComboExecptionForTFunc;
    /*
 *ZL 2018-8-3 10:01:50
 *方法描述：表格测试
 */
    @RequestMapping("/index/orgTable")
    public String orgTable(String menuId, Model model, HttpServletRequest request){

        model.addAttribute("menu", menuUtils.getMenuByRoleId(request,menuId));
        return "base/org/orgTable";
    }

    /*
    *ZL 2018-8-9 16:58:10
    *方法描述：树，测试
    */
    @RequestMapping("/org/showOrgPage")
    public String orgTree(String menuId, Model model, HttpServletRequest request){
        model.addAttribute("menu", menuUtils.getMenuByRoleId(request,menuId));
        return "base/org/org";
    }

      /*
      *ZL 2018-8-14 15:22:33
      *方法描述： 查询表格数据
      */
    @RequestMapping("/query/queryTable")
    @ResponseBody
    public ResultDTO queryTable(
            Pageable pageable ){
        PageInfo<Org> tabOrg = iOrgService.queryOrgPage(pageable.getPageNumber(),pageable.getPageSize());
        JSONObject map = new JSONObject();
        map.put("total",tabOrg.getTotal());
        map.put("rows",tabOrg.getList());
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /*
    *ZL 2018-8-16 13:56:28
    *方法描述：查询组织机构信息
    */
    @RequestMapping("/query/queryOrgTree")
    @ResponseBody
    public ResultDTO queryOrgTree(
    ){
        List<OrgZTreeNode> zTreeNodes = new ArrayList<>();
        List<Org> queryOrg = iOrgService.queryOrg();
        for(Org orgNode :queryOrg){
            OrgZTreeNode orgZTreeNode = new OrgZTreeNode();
            orgZTreeNode.setId(orgNode.getId());
            orgZTreeNode.setPid(orgNode.getParentId());
            orgZTreeNode.setName(orgNode.getOrgName());
            orgZTreeNode.setLevel(orgNode.getLevel());
            zTreeNodes.add(orgZTreeNode);
        }
        ResultDTO obj = ResultDTO.builder().data(zTreeNodes).build();
        return obj;
    }

    /*
   *ZL 2018-8-16 13:56:28
   *方法描述：编辑机构名称
   */
    @RequestMapping("/update/updateOrgName")
    @ResponseBody
    public ResultDTO updateOrgName(
                String treeId,String parentId,String treeLevel,String newName
    ){
        Org org = new Org();
        org.setId(treeId);
        org.setParentId(parentId);
        org.setLevel(treeLevel);
        org.setNewTreeName(newName);
        int count = iOrgService.updateOrgName(org);
        ResultDTO obj = ResultDTO.builder().isSuccess(true).build();
        return obj;

    }

    /*
     *ZL 2018-8-16 13:56:28
     *方法描述：删除机构，并且如果有子机构一并删除
     */
    @RequestMapping("/del/delOrg")
    @ResponseBody
    public ResultDTO delOrg(String treeId){
        Org org = new Org();

        Map<String,Object> orgMap = new HashMap<String,Object>();
          int countById = iOrgService.delOrgbyId(treeId);//删除当前所属节点
          int countByPid = iOrgService.delOrgbyPid(treeId);//当前节点作为父级节点，如果有对应机构一并删除
          ResultDTO obj = ResultDTO.builder().isSuccess(true).build();
          return obj;

    }

    /*
    *ZL 2018-8-16 13:56:28
    *方法描述：批量删除
    */
    @RequestMapping("/del/delOrgList")
    @ResponseBody
    public ResultDTO delOrgList(
          HttpServletRequest request
    ){
        String treeList[]=request.getParameterValues("treeNodeList[]");
        List<String> orgList = new ArrayList<>();
        Map<String,Object> orgMap = new HashMap<String,Object>();
        for( String orgId : treeList){
                Org org = new Org();
                org.setId(orgId);
                orgList.add(org.getId());
        }

        int count = iOrgService.clearChildren(orgMap);
        if (count >0){
            ResultDTO obj = ResultDTO.builder().isSuccess(true).build();
            return obj;
        }else {
            ResultDTO obj = ResultDTO.builder().isSuccess(false).build();
            return obj;
        }

    }

        /*
        *ZL 2018-8-17 15:02:31
        *方法描述：跳转到添加机构页面
        */
        @RequestMapping(value = "/org/toAddOrg",method = RequestMethod.GET)
        public String toAddOrg(int treeId,String parentId,String isParent,String treeLevel, Model model){
            model.addAttribute("treeId",treeId);
            model.addAttribute("parentId",parentId);
            model.addAttribute("isParent",isParent);
            model.addAttribute("treeLevel",treeLevel);
            return "base/org/addOrgDetail";
        }

    /**
     * 方法描述:新增机构基础信息
     * SJC 2018-9-25 20:00:57
     *
    */
    @RequestMapping("/org/addOrgDetail")
    @ResponseBody
    public ResultDTO addOrgDetail(@RequestParam String parentId,@RequestParam String treeLevel,@RequestParam String orgName,@RequestParam String address,
                                  @RequestParam String coordinate){
            String orgSn = iOrgService.queryUpMaxSn(parentId);
            Org org = new Org();
            org.setParentId(parentId);
            org.setOrgName(orgName);
            if(StringUtils.isEmpty(orgSn)){
                org.setSn("1");
            }else {
                org.setOrgSn(String.valueOf(Integer.parseInt(orgSn)+1));
            }
            org.setLevel(treeLevel);
            org.setAddress(address);
            org.setCoordinate(coordinate);
            iOrgService.addOrg(org);
            ResultDTO obj = ResultDTO.builder().data(org).build();
            return obj;
    }

    /**
     * 方法描述:展示组织机构详情
     * SJC 2018-9-10 16:20:13
     *
    */
    @RequestMapping(value = "/org/showUpdateOrgPage",method = RequestMethod.GET)
    public String showAddOrgPage(@RequestParam String treeId, Model model){
        //查询机构内容
        List<Map<String, Object>> orgList = iOrgService.queryOrgInfos(treeId);
        if(orgList != null || orgList.size()>0){
            Map<String,Object> data = orgList.get(0);
            model.addAttribute("org",data);
        }
        List<OrgAttach> oaList =iOrgService.queryOrgAttach(treeId);
        model.addAttribute("oaList",oaList);
        return "base/org/updateOrgDetail";
    }

    //绝对路径
    public String path(HttpServletRequest request){
        return accessPath+imgUrl;
    }

    @Value("${img.location}")
    String location;

    @Value("${img.accessPath}")
    String accessPath;

    //相对路径
    public String savePath(HttpServletRequest request){
//        String savePath = request.getSession().getServletContext().getRealPath(imgUrl);
        return location + imgUrl;
    }

    /**
     * 方法描述:新增内容块和图片上传
     * SJC 2018-8-26 17:28:56
     */
    @RequestMapping("/org/addOrgAttach")
    @ResponseBody
    public ResultDTO addOrgAttach(@RequestParam("file") MultipartFile file, @RequestParam("id") String id)  {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    if(StringUtils.isNotEmpty(id)){
                        //入库路径
                        String realPath = uploadUtiles.getCurrentAddress(imgUrl);
                        //上传路径
                        String savePath = uploadUtiles.getLocationAddress(imgUrl);
                        String fileName = uploadUtiles.getUpImg(savePath, file);
                        if (null != fileName && !"".equals(fileName)) {
                           OrgAttach orgAttach=OrgAttach.builder()
                                   .orgId(id)
                                   .attachUrl(realPath+fileName)
                                   .build();
                            iOrgService.addOrgAttach(orgAttach);
                            t.setIsSuccess(true);
                            t.setData(orgAttach.getAttachUrl());
                        } else {
                            t.setIsSuccess(false);
                            t.setMessage("图片上传失败");
                        }
                    }else {
                        t.setIsSuccess(false);
                        t.setMessage("请完成基本信息的添加");
                    }

                },
                (e, t) -> {
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("上传失败");
                }
        );
    }

    /**
     * 方法描述:图片上传 返回图片路径
     * SJC 2018-8-26 16:03:21
     */
    private String upImg(String savePath, MultipartFile file) {

        String relFn = null;
        try {
            if (null != file) {
                String filename = URLEncoder.encode(file.getOriginalFilename(), "utf-8");
                File filepath = new File(savePath, filename);
                //判断路径是否存在，如果不存在就创建一个
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();
                }
                InputStream inputStream = file.getInputStream();

                FileOutputStream fileOutputStream = null;
                String fnName = makeFileName(filename);
                relFn = fnName;
                byte[] data = new byte[1024];
                int len = 0;
                fileOutputStream = new FileOutputStream(savePath + fnName);
                while ((len = inputStream.read(data)) != -1) {
                    fileOutputStream.write(data, 0, len);
                }
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return relFn;
    }

    private static String makeFileName(String filename) { //2.jpg
        //为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
        String extname = filename.substring(filename.lastIndexOf("."), filename.length());
        return UUID.randomUUID().toString() + extname;
    }

    /**
     * 方法描述:修改组织机构基础信息
     * SJC 2018-9-10 21:20:52
    */
    @RequestMapping("/org/updateOrgDetail")
    @ResponseBody
    public ResultDTO updateOrgDetail(String orgId,String orgName,String address,String coordinate ){
        int count = iOrgService.updateOrgDetail(orgId,orgName,address,coordinate);
        JSONObject map = new JSONObject();
        map.put("count",count);
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:新增(修改)机构简介
     * SJC 2018-9-25 20:00:57
     *
     */
    @RequestMapping("/org/addOrgDesc")
    @ResponseBody
    public ResultDTO addOrgDetail(@RequestParam String orgId,@RequestParam String orgDesc){
        int count = iOrgService.updateOrgDesc(orgId,orgDesc);
        JSONObject map = new JSONObject();
        map.put("count",count);
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:新增机构招聘信息
     * SJC 2018-9-25 20:00:57
     *
     */
    @RequestMapping("/org/addRecruit")
    @ResponseBody
    public ResultDTO addRecruit(String orgId,String recruitInfo){
        String id = mysqlUtil.getMaxId("t_org_recruit");
        OrgRecruit orgRecruit = new OrgRecruit();
        orgRecruit.setId(id);
        orgRecruit.setOrgId(orgId);
        orgRecruit.setDesc(recruitInfo);
        int count = iOrgService.addRecruit(orgRecruit);
        JSONObject map = new JSONObject();
        map.put("id",orgRecruit.getId());
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:新增教研团队
     * SJC 2018-9-10 21:20:52
     */
    @RequestMapping("/org/addTeam")
    @ResponseBody
    public ResultDTO addTeam(String orgId,String teamInfo){
        String id = mysqlUtil.getMaxId("t_org_team");
        OrgTeam team = new OrgTeam();
        team.setId(id);
        team.setOrgId(orgId);
        team.setDesc(teamInfo);
        int count = iOrgService.addTeam(team);
        JSONObject map = new JSONObject();
        map.put("id",team.getId());
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:修改招聘简介
     * SJC 2018-9-28 21:40:56
     *
    */
    @RequestMapping("/org/updateRecruit")
    @ResponseBody
    public ResultDTO updateRecruit(String recruitId,String recruitInfo){
        int count = iOrgService.updateRecruit(recruitId,recruitInfo);
        JSONObject map = new JSONObject();
        map.put("count",count);
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:修改教研团队
     * SJC 2018-9-28 21:41:20
     *
    */
    @RequestMapping("/org/updateTeam")
    @ResponseBody
    public ResultDTO updateTeam(String teamId,String teamInfo){
        int count = iOrgService.updateTeam(teamId,teamInfo);
        JSONObject map = new JSONObject();
        map.put("count",count);
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class ReqTuple {
       Org org;
    }

    @PostMapping("/org/updateOrgBasic")
    @ResponseBody
    ResultDTO updateOrgBasic(@RequestBody ReqTuple reqTuple){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    iOrgService.updateOrgBasic(reqTuple.getOrg());
                },
                (e, t) -> {
                    t.setIsSuccess(false);
                    t.setMessage("组织机构移动异常");
                }
        );
    }
    @PostMapping("/org/delOrgAttach")
    @ResponseBody
    public ResultDTO delUserDesc(@RequestParam("id") String id, @RequestParam("imgUrl") String imgUrl) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    clearTempImg.clearImgs(imgUrl);
                    iOrgService.delOrgAttrch(id,imgUrl);
                    t.setIsSuccess(true);
                    t.setMessage("删除成功");
                }, (e, t) -> {
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("删除失败");
                }
        );
    }

    @GetMapping("/org/getLiveList/{orgId}")
    @ResponseBody
    ResultDTO getLiveList(@PathVariable String orgId,Pageable pageable){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    Map<String,Object> data = new HashMap<>();
                    PageInfo pageInfo=new PageInfo<>();
                    //管理员跟总校长
                    pageInfo=iOrgService.queryLiveList(pageable,orgId);
                    data.put("rows",pageInfo.getList());
                    data.put("total",pageInfo.getTotal());
                    t.setIsSuccess(true);
                    t.setMessage("查询成功");
                    t.setCode(200);
                    t.setData(data);
                },(e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("获取失败");
                }
        );
    }

    @GetMapping("/org/showAddLive/{liveId}/{orgId}/{type}")
    String showAddLive(@PathVariable String liveId,@PathVariable String orgId,@PathVariable String type, Model model){
        model.addAttribute("liveId",liveId);
        model.addAttribute("orgId",orgId);
        model.addAttribute("type",type);
        return "base/org/addLive";
    }

    @GetMapping("/org/getLiveDet/{liveId}")
    @ResponseBody
    ResultDTO getLiveDet(@PathVariable String liveId){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                   OrgLive orgLive=iOrgService.queryLiveByLiveId(liveId);
                   t.setMessage("查询成功");
                   t.setIsSuccess(true);
                   t.setData(orgLive);
                },(e,t)->{
                  e.printStackTrace();
                  t.setIsSuccess(false);
                  t.setMessage("获取失败");
                }
        );
    }

    @PostMapping("/org/addLive")
    @ResponseBody
    ResultDTO addLive(@RequestBody OrgReq orgReq){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                   OrgLive orgLive=orgReq.getOrgLive();
                   iOrgService.addLive(orgLive);
                   t.setIsSuccess(true);
                   t.setData(orgLive.getLiveId());
                   t.setMessage("添加成功");
                },(e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("获取失败");
                }
        );
    }

    @PostMapping("/org/updateLive")
    @ResponseBody
    ResultDTO updateLive(@RequestBody OrgReq orgReq){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    OrgLive orgLive=orgReq.getOrgLive();
                    int optCount= iOrgService.updateLive(orgLive);
                    t.setIsSuccess(optCount>0 ?true : false);
                    t.setData(optCount);
                    t.setMessage(optCount>0 ?"修改成功" : "修改失败");
                },(e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("获取失败");
                }
        );
    }

    @PostMapping("/org/addLiveAtt/{liveId}")
    @ResponseBody
    ResultDTO addLiveAtt(@PathVariable String liveId,@RequestParam("file") MultipartFile file, @RequestParam("id") String id){
         return iComboExecptionForTFunc.executeFlow(
             ResultDTO.builder().build(),
                 t->{
                     if(StringUtils.isNotEmpty(liveId)){
                         //入库路径
                         String realPath = uploadUtiles.getCurrentAddress(imgUrl);
                         //上传路径
                         String savePath = uploadUtiles.getLocationAddress(imgUrl);
                         String fileName = uploadUtiles.getUpImg(savePath, file);
                         if (null != fileName && !"".equals(fileName)) {
                             OrgAttach orgAttach= OrgAttach.builder()
                                     .orgId(liveId)
                                     .attachUrl(realPath+fileName)
                                     .orgType("live")
                                     .build();
                             iOrgService.addOrgAttach(orgAttach);
                             t.setIsSuccess(true);
                             t.setData(orgAttach.getAttachUrl());
                         } else {
                             t.setIsSuccess(false);
                             t.setMessage("图片上传失败");
                         }
                     }else {
                         t.setIsSuccess(false);
                         t.setMessage("请完成基本信息的添加");
                     }
                 },(e,t)->{
                     e.printStackTrace();
                     t.setIsSuccess(false);
                     t.setMessage("获取失败");
                 }
         );
    }

    @GetMapping("/org/delLiveByLiveId/{liveId}")
    @ResponseBody
    ResultDTO delLiveByLiveId(@PathVariable String liveId){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    int optCount=iOrgService.delLiveByLiveId(liveId);
                    t.setIsSuccess(optCount>0 ? true : false);
                    t.setMessage(optCount>0 ? "删除成功" : "删除失败");
                    t.setCode(optCount>0 ? 1 : 0);
                },(e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("获取失败");
                }
        );
    }

    @PostMapping("/org/delLiveAtt/{liveId}")
    @ResponseBody
    ResultDTO delLiveAtt(@PathVariable String liveId,@RequestParam("id") String id, @RequestParam("imgUrl") String imgUrl){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    clearTempImg.clearImgs(imgUrl);
                    iOrgService.delLiveAtt(liveId,imgUrl);
                    t.setIsSuccess(true);
                    t.setMessage("直播教室图片删除成功");
                }, (e, t) -> {
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("删除失败");
                }
        );
    }
}
